<template>
	<el-dialog title="修改角色名" :visible.sync="showDialog" :before-close="cancel" custom-class="change-role-name-dialog" width="499px">
		<el-form :model="roleData" label-width="100px" ref="formRef">
			<el-form-item label="角色名" :rules="roleData.roleNameRules" prop="roleName" :error="roleError">
				<el-input v-model="roleData.roleName" placeholder="请输入角色名" maxlength="16"></el-input>
			</el-form-item>

			<div class="btns">
				<el-button @click="cancel">取消</el-button>
				<el-button type="primary" @click="confirm">确认</el-button>
			</div>
		</el-form>
	</el-dialog>
</template>

<script>
import { mapState } from 'vuex';
import { validateRoleName } from '@/utils/formValidate';
import { changeRole } from '../../../api/api';
export default {
	components: {},
	props: {
		show: {
			type: Boolean,
			default: false
		},
		role: {
			type: Object,
			default: () => {}
		},
		roleList: {
			type: Array,
			default: () => []
		}
	},
	data() {
		return {
			roleData: {
				roleName: '',

				roleNameRules: [
					{ required: true, message: '请输入角色名', trigger: ['blur', 'change'] },
					{ validator: validateRoleName, trigger: 'blur' }
				]
			},
			showDialog: false,
			roleError: '' // 角色名校验失败
		};
	},
	watch: {
		show(newVal) {
			this.showDialog = newVal;
		},
		role: {
			immediate: true,
			handler: function (newVal) {
				this.roleData.roleName = newVal.name;
			},
			deep: true
		}
	},
	computed: {
		...mapState({
			loginInfo: state => state.login.userInfo
		})
	},
	mounted() {},
	methods: {
		confirm() {
			this.roleError = '';
			this.$refs['formRef'].validate(valid => {
				if (valid) {
					this.changeRole();
				}
			});
		},
		cancel() {
			this.$refs['formRef'].resetFields();
			this.$emit('close');
		},
		changeRole() {
			if (!this.roleData.roleName.trim()) {
				this.$message.warning('角色名不能为空');
				return;
			}
			this.roleData.roleName = this.roleData.roleName.trim();
			if (this.hasNameInList(this.roleData.roleName)) {
				this.$nextTick(() => {
					this.roleError = '角色名已存在';
				});
				return;
			}
			changeRole(this.role.id, this.roleData.roleName)
				.then(res => {
					const { code } = res.data;
					if (code === 200) {
						//
						this.$message.success('角色名修改成功');
						this.$emit('change', { role: this.role, name: this.roleData.roleName });
					} else {
						console.warn('change role  ', res);
						this.$message.warning('角色名修改失败');
					}
				})
				.catch(err => {
					console.error('change role error ', err);
					this.$message.warning('角色名修改失败');
				});
		},
		hasNameInList(name) {
			return this.roleList.find(item => item.name === name);
		}
	}
};
</script>

<style lang="less" scoped>
.change-role-name-dialog {
	.btns {
		text-align: right;
	}
	.head {
		padding: 20px 0;
	}
	.el-avatar > img {
		width: 100%;
	}
}
</style>
